package com.irun.sm.ui.demo.utils;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;

import android.graphics.Bitmap;

/***
 * @author huangsm
 * @date 2013-1-29
 * @email huangsanm@gmail.com
 * @desc bitmap缓存
 * 创建单实例【饿汗模式】
 */
public class BitmapCache {

	//实例化
	private static BitmapCache mCache = new BitmapCache();
	
	private Map<String, BitmapSoftRef> mCacheList;
	/** 垃圾Reference的队列（所引用的对象已经被回收，则将该引用存入队列中） */
	private ReferenceQueue<Bitmap> mQueue;

	private BitmapCache(){
		mCacheList = new HashMap<String, BitmapCache.BitmapSoftRef>();
		mQueue = new ReferenceQueue<Bitmap>();
	}
	
	public static BitmapCache getInstance(){
		return mCache;
	}
	
	private class BitmapSoftRef extends SoftReference<Bitmap> {
		private String key;
		public BitmapSoftRef(String _key, ReferenceQueue<Bitmap> queue, Bitmap r) {
			super(r, queue);
			key = _key;
		}
	}
	
	public Bitmap get(String fname, Bitmap bitmap){
		Bitmap bitp = null;
		if(mCacheList.containsKey(fname)){
			bitp = mCacheList.get(fname).get();
		}
		if(bitp == null){
			clearCache();
			mCacheList.put(fname, new BitmapSoftRef(fname, mQueue, bitmap));
			bitp = bitmap;
		}
		return bitp;
	}
	
	public void cleanCache(){
		BitmapSoftRef ref = null;
		while ((ref = (BitmapSoftRef) mQueue.poll()) != null) {
			mCacheList.remove(ref.key);
		}
	}
	
	public void clearCache() {
		cleanCache();
		mCacheList.clear();
		System.gc();
		System.runFinalization();
	}
}
